<template>
	<div class="update-analysis-container">
		<!-- 头部工具栏 -->
		<div class="analysis-header">
			<div class="header-title">
				<el-icon><ele-Refresh /></el-icon>
				<span>更新信息分析</span>
			</div>
			<div class="header-actions">
				<el-button type="primary" :icon="Refresh" @click="handleRefresh" :loading="loading" size="small">
					刷新数据
				</el-button>
			</div>
		</div>

		<!-- 统计卡片 -->
		<div class="stats-cards">
			<el-card class="stats-card">
				<div class="stats-content">
					<div class="stats-number">{{ totalAreas }}</div>
					<div class="stats-label">作业区总数</div>
				</div>
			</el-card>
			<el-card class="stats-card">
				<div class="stats-content">
					<div class="stats-number">{{ areasWithUpdates }}</div>
					<div class="stats-label">有更新的作业区</div>
				</div>
			</el-card>
			<el-card class="stats-card">
				<div class="stats-content">
					<div class="stats-number">{{ todayUpdatedAreas }}</div>
					<div class="stats-label">今日已更新</div>
				</div>
			</el-card>
			<el-card class="stats-card">
				<div class="stats-content">
					<div class="stats-number">{{ totalRecords }}</div>
					<div class="stats-label">总记录数</div>
				</div>
			</el-card>
		</div>

		<!-- 数据表格 -->
		<el-table 
			:data="tableData" 
			:loading="loading" 
			stripe 
			border 
			height="500" 
			class="analysis-table"
			@sort-change="handleSortChange"
		>
			<el-table-column prop="workAreaName" label="作业区名称" min-width="150" sortable="custom" />
			<el-table-column prop="totalCount" label="总记录数" width="120" sortable="custom" align="center" />
			<el-table-column prop="lastCreateTime" label="最后创建时间" min-width="180" sortable="custom">
				<template #default="{ row }">
					<span v-if="row.lastCreateTime">{{ formatDateTime(row.lastCreateTime) }}</span>
					<el-tag v-else type="info" size="small">无数据</el-tag>
				</template>
			</el-table-column>
			<el-table-column prop="lastUpdateTime" label="最后更新时间" min-width="180" sortable="custom">
				<template #default="{ row }">
					<span v-if="row.lastUpdateTime">{{ formatDateTime(row.lastUpdateTime) }}</span>
					<el-tag v-else type="info" size="small">未更新</el-tag>
				</template>
			</el-table-column>
			<el-table-column prop="lastUpdateUserName" label="最后更新人" min-width="120" sortable="custom">
				<template #default="{ row }">
					<span v-if="row.lastUpdateUserName">{{ row.lastUpdateUserName }}</span>
					<el-tag v-else type="info" size="small">-</el-tag>
				</template>
			</el-table-column>
			<el-table-column prop="todayUpdateStatus" label="今日更新状态" width="120" align="center" sortable="custom">
				<template #default="{ row }">
					<el-tag :type="row.todayUpdateStatus === '已更新' ? 'success' : 'warning'" size="small">
						{{ row.todayUpdateStatus }}
					</el-tag>
				</template>
			</el-table-column>
		</el-table>

		<!-- 分页 -->
		<div class="pagination-container">
			<el-pagination
				v-model:current-page="pagination.page"
				v-model:page-size="pagination.size"
				:total="pagination.total"
				:page-sizes="[10, 20, 50, 100]"
				layout="total, sizes, prev, pager, next, jumper"
				@size-change="handleSizeChange"
				@current-change="handleCurrentChange"
			/>
		</div>
	</div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch, computed } from 'vue';
import { ElMessage } from 'element-plus';
import { Refresh } from '@element-plus/icons-vue';
import { usePlanViewApi, type UpdateAnalysisInput, type UpdateAnalysisOutput } from '/@/api/plans/planView';

const planViewApi = usePlanViewApi();

// 定义Props
interface Props {
	filterParams: any;
}

const props = defineProps<Props>();

// 定义事件
const emit = defineEmits(['loading-change']);

// 响应式数据
const loading = ref(false);
const allTableData = ref<UpdateAnalysisOutput[]>([]);
const tableData = ref<UpdateAnalysisOutput[]>([]);

// 分页配置
const pagination = reactive({
	page: 1,
	size: 20,
	total: 0,
});

// 排序配置
const sortConfig = reactive({
	prop: '',
	order: '',
});

// 统计数据计算
const totalAreas = computed(() => allTableData.value.length);
const areasWithUpdates = computed(() => allTableData.value.filter(item => item.lastUpdateTime).length);
const todayUpdatedAreas = computed(() => allTableData.value.filter(item => item.todayUpdateStatus === '已更新').length);
const totalRecords = computed(() => allTableData.value.reduce((sum, item) => sum + item.totalCount, 0));

// 加载更新分析数据
const loadUpdateAnalysisData = async () => {
	try {
		loading.value = true;
		emit('loading-change', true);

		// 构建请求参数
		const params: UpdateAnalysisInput = {
			workTime: props.filterParams?.workTime,
			className: props.filterParams?.className,
			workAreaId: props.filterParams?.workAreaId,
		};

		console.log('发送更新分析查询参数:', params);
		const response = await planViewApi.getUpdateAnalysisData(params);
		console.log('更新分析查询响应:', response);
		
		allTableData.value = response.data.result || [];
		
		// 应用排序
		applySorting();
		
		// 更新分页
		updatePagination();
		
	} catch (error) {
		console.error('加载更新分析数据失败:', error);
		ElMessage.error('加载更新分析数据失败');
		allTableData.value = [];
		updatePagination();
	} finally {
		loading.value = false;
		emit('loading-change', false);
	}
};

// 应用排序
const applySorting = () => {
	if (!sortConfig.prop) {
		return;
	}

	allTableData.value.sort((a, b) => {
		const aVal = a[sortConfig.prop as keyof UpdateAnalysisOutput];
		const bVal = b[sortConfig.prop as keyof UpdateAnalysisOutput];
		
		let result = 0;
		if (aVal < bVal) result = -1;
		else if (aVal > bVal) result = 1;
		
		return sortConfig.order === 'ascending' ? result : -result;
	});
};

// 更新分页数据
const updatePagination = () => {
	pagination.total = allTableData.value.length;
	const start = (pagination.page - 1) * pagination.size;
	const end = start + pagination.size;
	tableData.value = allTableData.value.slice(start, end);
};

// 处理排序变化
const handleSortChange = ({ prop, order }: any) => {
	sortConfig.prop = prop;
	sortConfig.order = order;
	applySorting();
	updatePagination();
};

// 处理分页变化
const handleSizeChange = (size: number) => {
	pagination.size = size;
	pagination.page = 1;
	updatePagination();
};

const handleCurrentChange = (page: number) => {
	pagination.page = page;
	updatePagination();
};

// 刷新数据
const handleRefresh = () => {
	loadUpdateAnalysisData();
};

// 格式化日期时间
const formatDateTime = (dateTime: string | null) => {
	if (!dateTime) return '';
	return new Date(dateTime).toLocaleString('zh-CN');
};


// 监听筛选条件变化
watch(
	() => props.filterParams,
	(newParams) => {
		console.log('UpdateAnalysisTable watch 触发, 新参数:', newParams);
		loadUpdateAnalysisData();
	},
	{ deep: true }
);

// 监听分页变化时重新分页
watch(
	() => [pagination.page, pagination.size],
	() => {
		updatePagination();
	}
);

// 组件挂载
onMounted(() => {
	loadUpdateAnalysisData();
});
</script>

<style lang="scss" scoped>
.update-analysis-container {
	padding: 20px;
	background-color: #fff;
	border-radius: 4px;

	.analysis-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20px;
		padding: 16px;
		background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
		border-radius: 4px;
		color: white;

		.header-title {
			display: flex;
			align-items: center;
			font-size: 18px;
			font-weight: 600;
			gap: 8px;
		}

		.header-actions {
			:deep(.el-button--primary) {
				background: rgba(255, 255, 255, 0.2);
				border-color: rgba(255, 255, 255, 0.3);
				
				&:hover {
					background: rgba(255, 255, 255, 0.3);
					border-color: rgba(255, 255, 255, 0.5);
				}
			}
		}
	}

	.stats-cards {
		display: grid;
		grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
		gap: 16px;
		margin-bottom: 20px;

		.stats-card {
			border-radius: 4px;
			border: 1px solid var(--el-border-color-light);
			
			:deep(.el-card__body) {
				padding: 16px;
			}

			.stats-content {
				text-align: center;

				.stats-number {
					font-size: 28px;
					font-weight: bold;
					color: var(--el-color-primary);
					margin-bottom: 8px;
				}

				.stats-label {
					font-size: 14px;
					color: var(--el-text-color-regular);
				}
			}
		}
	}

	.analysis-table {
		border-radius: 4px;
		overflow: hidden;

		:deep(.el-table__header) {
			background-color: #f8f9fa;
		}

		:deep(.el-table__row) {
			&:hover {
				background-color: #f5f7fa;
			}
		}
	}

	.pagination-container {
		display: flex;
		justify-content: center;
		margin-top: 20px;
	}
}

@media (max-width: 768px) {
	.update-analysis-container {
		padding: 15px;

		.analysis-header {
			flex-direction: column;
			gap: 16px;
			text-align: center;

			.header-actions {
				width: 100%;
			}
		}

		.stats-cards {
			grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
		}

		.analysis-table {
			:deep(.el-table__body-wrapper) {
				overflow-x: auto;
			}
		}
	}
}
</style>